<template>
  <div class="btn-card">
    <div class="echarts-dom">
      <modelTitle v-if="title" :title="title">
        <div class="model-title-slot">
          <span v-if="rightText" class="right-text">{{ rightText }}</span>
          <px-button v-if="button && linesListValue" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
        </div>
      </modelTitle>
      <div v-if="linesListValue" class="echarts-dom-btn">
        <px-radio-group v-model="allLines" @change="handleChangeLines">
          <px-radio-button label="1">全部</px-radio-button>
          <px-radio-button label="2">清空</px-radio-button>
        </px-radio-group>
        <px-checkbox-group v-if="queryTimeType" v-model="addLines" @change="handleAddLines">
          <px-checkbox-button label="1">同比</px-checkbox-button>
          <px-checkbox-button label="2">环比</px-checkbox-button>
        </px-checkbox-group>
      </div>
      <div v-if="linesListValue" ref="chartContainer" :style="{ width: width, height: height }" />
      <div v-else class="echarts-empty">
        <px-empty :image-size="imageSize" />
      </div>
    </div>
    <div v-if="showDetails" class="con_table">
      <tablePaginated :table-data="tableData" :table-colums="tableColums" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, nextTick, computed } from "vue";
import tablePaginated from "@/views/common/energy/components/tablePaginated.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import * as echarts from "echarts";
import { subSystemCurveIndicator } from "@/api/modules/energy";

const chartContainer = ref(null);
let chartInstance = null;
const props = defineProps({
  width: {
    type: String,
    default: ""
  },
  height: {
    type: String,
    default: ""
  },
  queryParams: {
    type: Object,
    default: () => {}
  },
  dateRange: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: ""
  },
  button: {
    type: String,
    default: ""
  },
  rightText: {
    type: String,
    default: ""
  },
  dictKey: {
    type: String,
    default: ""
  },
  energyType: {
    type: String,
    default: ""
  },
  className: {
    type: String,
    default: ""
  },
  queryTimeType: {
    type: String,
    default: ""
  },
  showBtn: {
    type: Boolean,
    default: true
  },
  isSerch: {
    type: Boolean,
    default: false
  },
  showDetails: {
    type: Boolean,
    default: false
  },
  imageSize: {
    type: Number,
    default: 100
  }
});

const tableData = ref([]);
const tableColums = ref([
  { value: "deptName", name: "科室", width: "" },
  { value: "systemName", name: "系统", width: "" },
  { value: "energyTypeName", name: "能耗类型", width: "" },
  { value: "valueFormat", name: "用量", width: "" },
  { value: "unit", name: "单位", width: "" },
  { value: "time", name: "时间", width: "" }
]);

// 曲线图 option
const botOptions = ref({
  tooltip: {
    trigger: "axis"
  },
  legend: {
    type: "scroll", // 设置图例分页类型为滚动
    icon: "rect",
    orient: "horizontal", // 水平排列
    right: "center", // 水平居中
    itemWidth: 37, // 图例标记的图形宽度
    itemHeight: 13, // 图例标记的图形高度
    selected: {},
    data: []
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {
    type: "value",
    name: ""
  },
  series: []
});

const allLines = ref("1");
const addLines = ref([]);

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const clickHandler = () => emits("btn-click");

// 全部/清空
const handleChangeLines = (val: string) => {
  if (chartContainer.value) {
    if (val === "1") {
      chartInstance.setOption(botOptions.value);
    } else {
      let options = JSON.parse(JSON.stringify(botOptions.value));
      Object.keys(options.legend.selected).forEach(item => {
        options.legend.selected[item] = false;
      });
      chartInstance.setOption(options);
    }
  }
};

// 同环比点击
const handleAddLines = async (val: string[]) => {
  if (compareIndicator.value.name) {
    await nextTick();
    getData(compareIndicator.value);
  } else {
    addLines.value = [];
    return;
  }
};

onMounted(async () => {
  await nextTick();
  getData(compareIndicator.value);
});

const resize = () => {
  chartInstance && chartInstance.resize();
};

interface compareIndicatorType {
  name: string;
  indicatorKey: string;
  unit: string;
}
// 存储当前点击的指标
const compareIndicator = ref<compareIndicatorType>({
  name: "",
  indicatorKey: "",
  unit: ""
});
// 获取参数
const getParams = (val: any) => {
  return {
    startTime: props.dateRange.length ? props.dateRange[0] : props.queryParams.startTime,
    endTime: props.dateRange.length ? props.dateRange[1] : props.queryParams.endTime,
    queryTimeGranularity: props.queryTimeType ? "" : props.queryParams.queryTimeGranularity,
    energyType: props.energyType,
    className: props.className,
    queryTimeType: props.queryTimeType,
    dictKey: props.dictKey,
    needYoy: addLines.value.includes("1") ? "Y" : "N",
    needMom: addLines.value.includes("2") ? "Y" : "N",
    needAllPage: "Y",
    compareIndicator: {
      name: val.name,
      indicatorKey: val.indicatorKey,
      unit: val.unit
    }
  };
};

// 获取对象数组某一项value组成的数组
const getValueList = (arr: any[], key: number | string) => {
  let valueList = [];
  arr.forEach(item => {
    valueList.push(item[key]);
  });
  return valueList;
};

// 用于存储子系统指标
const indicatorKeyList = ref<any>([]);
const linesListValue = ref<any>([]);
// 获取数据
const getData = async (v: any) => {
  let res: any = await subSystemCurveIndicator(getParams(v));
  let legendData = [];
  let xData = [];
  let seriesData = [];
  let seriesDataCompareIndicator = [];
  let unit = "";
  let legendSelected = {};
  linesListValue.value = res?.indicatorList && res?.indicatorList.length;
  allLines.value = "1";
  if (!linesListValue.value) return;
  let resData: any = JSON.parse(JSON.stringify(res));
  resData.indicatorList.forEach((item: any) => {
    legendData.push(item.label.name);
    legendSelected[item.label.name] = true;
    unit = item.label.unit;
    xData = getValueList(item.detail, "timeFormat");
    seriesData.push({
      name: item.label.name,
      type: "line",
      data: getValueList(item.detail, "value"),
      emphasis: {
        focus: "series"
      }
    });
    seriesDataCompareIndicator.push({
      name: item.label.name,
      indicatorKey: item.label.indicatorKey,
      unit: item.label.unit
    });
  });
  tableData.value = resData.allPage;
  indicatorKeyList.value = seriesDataCompareIndicator;
  botOptions.value.legend.selected = legendSelected;
  botOptions.value.legend.data = legendData;
  botOptions.value.xAxis.data = xData;
  botOptions.value.series = seriesData;
  botOptions.value.yAxis.name = unit;
  initChart();
};

// defineExpose({
//   getData
// });

const currentLine = ref("");

watch(currentLine, (oldVal, newVal) => {
  if (oldVal !== newVal) {
    addLines.value = [];
  }
});

const initChart = async () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.clear();
    chartInstance.setOption(botOptions.value);
    chartInstance.resize();
    window.addEventListener("resize", () => resize());
    chartInstance.on("click", e => {
      currentLine.value = e.seriesName;
      let options = JSON.parse(JSON.stringify(botOptions.value));
      let selectedName = e.seriesName;
      Object.keys(options.legend.selected).forEach(item => {
        if (item !== selectedName) {
          options.legend.selected[item] = !options.legend.selected[item];
        }
      });
      allLines.value = "";
      const { name, indicatorKey, unit } = indicatorKeyList.value.find(item => item.name === selectedName);
      compareIndicator.value = { name, indicatorKey, unit };
      chartInstance.clear();
      chartInstance.setOption(options);
      chartInstance.resize();
      window.addEventListener("resize", () => resize());
    });
    // 全部、清空与图例联动
    chartInstance.on("legendselectchanged", e => {
      const showAll = Object.keys(e.selected).every(item => e.selected[item]);
      const hideAll = Object.keys(e.selected).every(item => !e.selected[item]);
      if (showAll) {
        allLines.value = "1";
      } else if (hideAll) {
        allLines.value = "2";
      } else {
        allLines.value = "";
      }
    });
  }
};

watch(
  () => props.queryTimeType,
  newValue => {
    if (newValue) {
      getData(compareIndicator.value);
    }
  }
);
watch(
  () => props.isSerch,
  newValue => {
    getData(compareIndicator.value);
    console.log(newValue);
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
</script>

<style lang="scss" scoped>
.btn-card {
  width: 100%;

  .echarts-dom {
    position: relative;
    padding: 16px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);

    .echarts-dom-btn {
      position: absolute;
      top: 46px;
      right: 6px;
      z-index: 999;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      background-color: #fff;

      .px-checkbox-group {
        margin-left: 50px;
      }
    }
  }

  .con_table {
    width: 100%;
    padding: 16px;
    margin-top: 16px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);
  }
}
</style>
